package goboot

import (
	"flag"
	"gitee.com/xiaotaozi/goboot/config"
	"gitee.com/xiaotaozi/goboot/logging"
	"github.com/spf13/viper"
)

/**
运行一个go程序
*/
func Run() GobootApp {
	return New(WithDefaultConfigFile("configFile","application.yml"), WithZapLogging())
}

/**
默认加载application.yaml, 选项名为configFile
 */
func WithDefaultConfigFile(configfileOption,configFileDefault string) GobootAppOption{
	return func(app GobootApp) {
		// 解析命令行参数
		configFile := flag.String(configfileOption, configFileDefault, "specify config file location")
		flag.Parse()
		// 初始化viper
		vp,err := config.NewViper(*configFile)
		if err != nil{
			panic(err)
		}
		app.SetViper(vp)
		app.GetContainer().Provide(func() *viper.Viper {
			return vp
		})
	}
}

/**
默认使用zaplog
 */
func WithZapLogging() GobootAppOption{
	return func(app GobootApp){
		err := app.GetContainer().Provide(logging.NewLogger);if err != nil {
			panic(err)
		}
		// 注册关闭函数
		app.RegisterShutdownFn(func() {
			_ = app.GetContainer().Invoke(logging.CloseLogger)
		})
	}
}

